﻿using Cysharp.Threading.Tasks;
using System;
using System.Collections;
using UnityEngine;
using YooAssetHandle = YooAsset.AssetHandle;

namespace MFramework
{
    public class AssetHandle
    {
        private YooAssetHandle handle;

        public event Action<AssetHandle> Completed;
        public UnityEngine.Object AssetObject { get => handle.AssetObject; }

        public bool IsValid
        {
            get => handle.IsValid;
        }

        internal void Init(YooAssetHandle handle)
        {
            this.handle = handle;
            this.handle.Completed += (YooAssetHandle _handle) =>
            {
                this.Completed?.Invoke(this);
            };
        }

        public void Release()
        {
            this.handle.Release();
        }

        public GameObject InstantiateSync()
        {
            return this.handle.InstantiateSync();
        }

        public GameObject InstantiateSync(Transform parent)
        {
            return this.handle.InstantiateSync(parent);
        }

        public void InstantiateAsync(Action<GameObject> onCompleted)
        {
            var operation = this.handle.InstantiateAsync();
            operation.Completed += (YooAsset.AsyncOperationBase _)=>
            {
                onCompleted?.Invoke(operation.Result);
            };
        }
    }
}